package etnorservice.etnor_service.controller;/**
 * Created with IntelliJ IDEA.
 * @Author: cc
 * @Date: 2024/08/13/12:15
 **/
import etnorservice.etnor_service.domain.po.DeviceInfo;
import etnorservice.etnor_service.service.DeviceInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;

@RestController
public class DeviceInfoController {
    @Autowired
    private DeviceInfoService deviceInfoService;

    @PostMapping("/device-info")
    public String saveDeviceInfo(@RequestBody String userAgent, HttpServletRequest request) {
        String ipAddress = getIpAddress(request);
        DeviceInfo deviceInfo=new DeviceInfo();
        deviceInfo.setIpAddress(ipAddress);
        deviceInfo.setUserAgent(userAgent);
        deviceInfoService.saveInfo(deviceInfo);
        return "Device information saved successfully";
    }

    private String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }


}

